package com.qlogic.commons.platform.impls.lucene.handler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;

public class PlainTextHandler implements ContentHandler {

	public String getText(InputStream is, String encoding) throws ContentHandlerException {
		String bodyText = "";
		try {
			BufferedReader br = null;
			if (encoding != null) {
				br = new BufferedReader(new InputStreamReader(is, encoding));
			} else {
				br = new BufferedReader(new InputStreamReader(is));
			}
			String line = null;
			while ((line = br.readLine()) != null) {
				bodyText += line;
			}
			br.close();
		} catch (IOException e) {
			throw new ContentHandlerException("Cannot read the text document", e);
		}
		if (bodyText == null || bodyText.equals ("")) {
			return null;
		}
		return bodyText;
	}

	public Document getDocument(InputStream is, String encoding) throws ContentHandlerException {
		String bodyText = getText(is, encoding);
		if (bodyText != null) {
			Document doc = new Document();
			doc.add(new Field (BODY, bodyText, Field.Store.NO, Field.Index.TOKENIZED));
			return doc;
		}
		return null;
	}

}
